package com.lukebang.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import java.io.InputStream;

//七牛上传图片的工具类
public class QINIUUploadUtil {
	// 设置好账号的ACCESS_KEY和SECRET_KEY
	// String ACCESS_KEY = "7iWH7YPKy66hAhyR-RbUTqHbFw1SFARjRBHU3BQr";
	// String SECRET_KEY = "o_vDvsVLoFm9Pxd-FqmOK-0tfCHgOSv9_9-oet6d";
	static String ACCESS_KEY = "dOcl9dBDG3slxqYH0ISdXwv6slScN3ovAHrAocgm";
	static String SECRET_KEY = "WiWNmd-n4aT-OTkowxenXes6ETul7JcvUo4-dGr8";
	// 要上传的空间
	static String bucketname = "test";
	// 构造一个带指定Zone对象的配置类
	static Configuration cfg = new Configuration(Zone.zone1());
	// ...其他参数参考类注释
	static UploadManager uploadManager = new UploadManager(cfg);

	// 默认不指定key的情况下，以文件内容的hash值作为文件名
	public static void uploadByStream(InputStream stream) {
		String key = null;
		try {
			Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
			String upToken = auth.uploadToken(bucketname);
			try {
				Response response = uploadManager.put(stream, key, upToken, null, null);
				// 解析上传成功的结果
				DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
				System.out.println(putRet.key);
				System.out.println(putRet.hash);
			} catch (QiniuException ex) {
				Response r = ex.response;
				System.err.println(r.toString());
				try {
					System.err.println(r.bodyString());
				} catch (QiniuException ex2) {
					// ignore
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// 默认不指定key的情况下，以文件内容的hash值作为文件名
	public static String uploadByByte(byte[] uploadBytes) {
		String key = null;
		try {
			Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
			String upToken = auth.uploadToken(bucketname);
			try {
				Response response = uploadManager.put(uploadBytes, key, upToken);
				// 解析上传成功的结果
				DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
				System.out.println("byte     " + putRet.key);
				System.out.println("byte     " + putRet.hash);
				return putRet.hash;
			} catch (QiniuException ex) {
				Response r = ex.response;
				System.err.println(r.toString());
				try {
					System.err.println(r.bodyString());
				} catch (QiniuException ex2) {
					// ignore
				}
				return null;
			}
		} catch (Exception ex) {
			return null;
		}
	}
}
